import React, {useRef, useState} from 'react'
import SwiperCore, {Autoplay, Pagination, EffectCoverflow} from 'swiper'
import {Swiper, SwiperSlide} from 'swiper/react'
import './CardCarousel.css'

import 'swiper/swiper-bundle.css'
// 在必要的时候初始化Swiper
SwiperCore.use([Autoplay, Pagination])

// import required modules

const CardCarousel = () => {
  const swiperRef = useRef<any>(null)
  const [swiper, setSwiper] = useState<SwiperCore>()
  const [activeIndex, setActiveIndex] = useState(0)
  const handleContainerClick = (
    event: React.MouseEvent<HTMLDivElement, MouseEvent>
  ) => {
    const x = event.clientX
    const container = swiperRef.current
    if (!container) return
    const containerRect = container.getBoundingClientRect()
    const containerLeft = containerRect.left
    const containerWidth = containerRect.width
    const containerRight = containerLeft + containerWidth
    if (x < containerLeft || x > containerRight) return

    const left = container.offsetLeft
    const width = container.offsetWidth
    if (x < left + width / 2) {
      swiper?.slidePrev()
    } else {
      swiper?.slideNext()
    }
  }

  return (
    <div ref={swiperRef} className="mySwiper" onClick={handleContainerClick}>
      <>
        <Swiper
          onSlideChange={swiper => setActiveIndex(swiper.activeIndex)}
          onSwiper={swiper => setSwiper(swiper)}
          effect={'coverflow'}
          grabCursor={true}
          loop={true}
          centeredSlides={true}
          slidesPerView={2}
          coverflowEffect={{
            rotate: 0,
            stretch: 40,
            depth: 160,
            modifier: 2,
          }}
          pagination={true}
          modules={[EffectCoverflow, Pagination]}
          className="mySwiper"
        >
          <SwiperSlide className="swiperSlide">
            <img src="https://swiperjs.com/demos/images/nature-1.jpg" />
          </SwiperSlide>
          <SwiperSlide className="swiperSlide">
            <img src="https://swiperjs.com/demos/images/nature-2.jpg" />
          </SwiperSlide>
          <SwiperSlide className="swiperSlide">
            <img src="https://swiperjs.com/demos/images/nature-3.jpg" />
          </SwiperSlide>
          <SwiperSlide className="swiperSlide">
            <img src="https://swiperjs.com/demos/images/nature-4.jpg" />
          </SwiperSlide>
          <SwiperSlide className="swiperSlide">
            <img src="https://swiperjs.com/demos/images/nature-5.jpg" />
          </SwiperSlide>
          <SwiperSlide className="swiperSlide">
            <img src="https://swiperjs.com/demos/images/nature-6.jpg" />
          </SwiperSlide>
        </Swiper>
      </>
    </div>
  )
}
export default CardCarousel
